<?php
/**
 * Mechanism
 * 
 * LICENSE
 * 
 * This file is private intellectual property of the author. 
 * All rights reserved. Copying and illegal using is punishable by law.
 * 
 * @copyright Copyright (c) 2011 BreatheInMyVoid ( BreatheInMyVoid@gmail.com )
 */

namespace Mechanism\Loader\Resource {
	class Controller extends Resource {
		protected $controllers_dir = 'controllers';
		protected $controllers_namespace = 'Controller';

		public function load( $name, $module = null ) {
			$name = ucfirst( $name );

			/* Load from global application path or module path */
			if ( null === $module ) {
				$path = $this->app_path 
						. $this->ds
						. $this->get_controllers_dir( ) 
						. $this->ds
						. $name
						. '.php';
				
				$target = $this->get_app_namespace( )
						  . '\\' 
						  . $this->get_controllers_namespace( )
						  . '\\' 
						  . $name;
			} else {
				$module_namespace = ucfirst( $module );

				$path = $this->app_path 
						. $this->ds
						. $this->get_modules_dir( )
						. $this->ds
						. $module
						. $this->ds
						. $this->get_controllers_dir( ) 
						. $this->ds
						. $name
						. '.php';
				
				$target = $this->get_app_namespace( )
						  . '\\' 
						  . $this->get_modules_namespace( )
						  . '\\'
						  . $module_namespace
						  . '\\'
						  . $this->get_controllers_namespace( )
						  . '\\' 
						  . $name;
			}

			if ( file_exists( $path ) && is_readable( $path ) ) {
				require_once $path;
			} else {
				throw new Exception\Nonest( 'Controller not found' );
			}


			if( class_exists( $target, false ) ) {
				return new $target;
			} else {
				throw new Exception\Runtime( 'Invalid controller' );
			}
		}

		public function set_actions_dir( $name ) {
			$this->actions_dir = $name;
		}

		public function set_actions_namespace( $name ) {
			$this->actions_namespace = $name;
		}

		public function set_controller_name( $name ) {
			$this->controller_name = $name;
		}

		public function set_controllers_dir( $name ) {
			$this->controllers_dir = $name;
		}

		public function set_controllers_namespace( $namespace ) {
			$this->controllers_namespace = $namespace;
		}

		public function get_actions_dir( ) {
			return $this->actions_dir;
		}

		public function get_actions_namespace( ) {
			return $this->actions_namespace;
		}

		public function get_controller_name( ) {
			return $this->controller_name;
		}

		public function get_controllers_dir( ) {
			return $this->controllers_dir;
		}

		public function get_controllers_namespace( ) {
			return $this->controllers_namespace;
		}
	}
}
